package fr.louloutes.lolshooter;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

/**
 * @author Louloute Settings Activity - Permet au joueur d'indiquer ses
 *         préférences de jeu - nom du joueur - difficulté - rareté des bonus -
 *         musique coupée ou active - effets sonors coupés ou actifs - ...
 */

// for associated code, see
// http://www.informit.com/store/product.aspx?isbn=9780321673350

public class SettingsAct extends LOLActivity
{

	SharedPreferences mGameSettings;
	static final int DATE_DIALOG_ID = 0;
	static final int PASSWORD_DIALOG_ID = 1;

	/** Called when the activity is first created. */
	@Override
	public void onCreate( Bundle savedInstanceState )
	{
		Utils.Log( "Settings onCreate", this );
		super.onCreate( savedInstanceState );
		setContentView( R.layout.settings );

		// Initialize prference variable
		mGameSettings = getSharedPreferences( GAME_PREFERENCES,
				Context.MODE_PRIVATE );

		// Init player name
		initNicknameEntry();

		// Init email
		initEmailEntry();

		// Init password
		initPasswordChooser();

		// Initialize the Date picker
		initDatePicker();

		// Dealing with gender
		initGenderSpinner();

	}

	private void initNicknameEntry()
	{
		final EditText playerName_EditText = ( EditText ) findViewById( R.id.editText_nickname );
		if ( mGameSettings.contains( GAME_PREFERENCES_NICKNAME ) )
		{
			playerName_EditText.setText( mGameSettings.getString(
					GAME_PREFERENCES_NICKNAME, "" ) );
		}
		playerName_EditText.setOnKeyListener( new View.OnKeyListener()
		{
			@Override
			public boolean onKey( View v, int keyCode, KeyEvent event )
			{
				if ( ( event.getAction() == KeyEvent.ACTION_DOWN )
						&& ( keyCode == KeyEvent.KEYCODE_ENTER ) )
				{
					String playerNameToSave = playerName_EditText.getText()
							.toString();
					// Save player name in global preferences
					Editor editor = mGameSettings.edit();
					editor.putString( GAME_PREFERENCES_NICKNAME,
							playerNameToSave );
					editor.commit();
					return true;
				}
				return false;
			}
		} );
	}

	private void initEmailEntry()
	{
		final EditText playerMail_EditText = ( EditText ) findViewById( R.id.editText_mail );
		if ( mGameSettings.contains( GAME_PREFERENCES_EMAIL ) )
		{
			playerMail_EditText.setText( mGameSettings.getString(
					GAME_PREFERENCES_EMAIL, "" ) );
		}
		playerMail_EditText.setOnKeyListener( new View.OnKeyListener()
		{
			@Override
			public boolean onKey( View v, int keyCode, KeyEvent event )
			{
				if ( ( event.getAction() == KeyEvent.ACTION_DOWN )
						&& ( keyCode == KeyEvent.KEYCODE_ENTER ) )
				{
					String playerMailToSave = playerMail_EditText.getText()
							.toString();
					// Save player mail in global preferences
					Editor editor = mGameSettings.edit();
					editor.putString( GAME_PREFERENCES_EMAIL, playerMailToSave );
					editor.commit();
					return true;
				}
				return false;
			}
		} );
	}

	private void initPasswordChooser()
	{
		// Set password info
		TextView passwordInfo = ( TextView ) findViewById( R.id.textView_pwd_info );
		if ( mGameSettings.contains( GAME_PREFERENCES_PASSWORD ) )
		{
			passwordInfo.setText( R.string.settings_pwd_set );
		} else
		{
			passwordInfo.setText( R.string.settings_pwd_not_set );
		}
		// Handle password setting dialog
		Button setPassword = ( Button ) findViewById( R.id.settings_button_pwd );
		setPassword.setOnClickListener( new View.OnClickListener()
		{
			@Override
			public void onClick( View v )
			{
				showDialog( PASSWORD_DIALOG_ID );
			}
		} );
	}

	private void initDatePicker()
	{
		// Set password info
		TextView dobInfo = ( TextView ) findViewById( R.id.textView_birthdate_info );
		if ( mGameSettings.contains( GAME_PREFERENCES_DOB ) )
		{
			dobInfo.setText( DateFormat.format( "MMMM dd, yyyy",
					mGameSettings.getLong( GAME_PREFERENCES_DOB, 0 ) ) );
		} else
		{
			dobInfo.setText( R.string.settings_birthdate_not_set );
		}
		// Handle date picking dialog
		Button pickDate = ( Button ) findViewById( R.id.settings_button_birthdate );
		pickDate.setOnClickListener( new View.OnClickListener()
		{
			@Override
			public void onClick( View v )
			{
				showDialog( DATE_DIALOG_ID );
			}
		} );
	}

	private void initGenderSpinner()
	{
		// Populate Spinner control with genders
		final Spinner spinner = ( Spinner ) findViewById( R.id.settings_spinner_gender );
		ArrayAdapter<?> adapter = ArrayAdapter.createFromResource( this,
				R.array.genders, android.R.layout.simple_spinner_item );
		adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
		spinner.setAdapter( adapter );
		if ( mGameSettings.contains( GAME_PREFERENCES_GENDER ) )
		{
			spinner.setSelection( mGameSettings.getInt(
					GAME_PREFERENCES_GENDER, 0 ) );
		}
		// Handle spinner selections
		spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener()
		{
			@Override
			public void onItemSelected( AdapterView<?> parent,
					View itemSelected, int selectedItemPosition, long selectedId )
			{
				Editor editor = mGameSettings.edit();
				editor.putInt( GAME_PREFERENCES_GENDER, selectedItemPosition );
				editor.commit();
			}

			@Override
			public void onNothingSelected( AdapterView<?> parent )
			{
			}
		} );
	}

	@Override
	protected Dialog onCreateDialog( int id )
	{
		Utils.Log( "1", this );
		switch ( id )
		{
		// TODO Problèpme à résoudre ici, ce Dialog ne veut pas se lancer
		// correctement
		// Idem pour l'équivalent dans le programme ref.
		/*		case DATE_DIALOG_ID:
					Utils.Log( "2", this );
					final TextView dob = ( TextView ) findViewById( R.id.textView_birthdate_info );
					Utils.Log( "3", this );

					DatePickerDialog dateDialog = new DatePickerDialog( this,
							new DatePickerDialog.OnDateSetListener()
							{
								@Override
								public void onDateSet( DatePicker view, int year,
										int monthOfYear, int dayOfMonth )
								{
									Utils.Log( "4", SettingsAct.this );
									Time dateOfBirth = new Time();
									Utils.Log( "5", SettingsAct.this );
									dateOfBirth.set( dayOfMonth, monthOfYear, year );
									Utils.Log( "6", SettingsAct.this );
									long dtDob = dateOfBirth.toMillis( true );
									Utils.Log( "7", SettingsAct.this );
									dob.setText( DateFormat.format( "MMMM dd, yyyy",
											dtDob ) );
									Utils.Log( "8", SettingsAct.this );
									Editor editor = mGameSettings.edit();
									editor.putLong( GAME_PREFERENCES_DOB, dtDob );
									editor.commit();
									Utils.Log( "9", SettingsAct.this );
								}
							}, 0, 0, 0 );
					return dateDialog;
		*/
		case PASSWORD_DIALOG_ID:
			LayoutInflater inflater = ( LayoutInflater ) getSystemService( Context.LAYOUT_INFLATER_SERVICE );
			final View layout = inflater.inflate( R.layout.password_dialog,
					( ViewGroup ) findViewById( R.id.root ) );
			final EditText p1 = ( EditText ) layout
					.findViewById( R.id.EditText_Pwd1 );
			final EditText p2 = ( EditText ) layout
					.findViewById( R.id.EditText_Pwd2 );
			final TextView error = ( TextView ) layout
					.findViewById( R.id.TextView_PwdProblem );
			p2.addTextChangedListener( new TextWatcher()
			{
				@Override
				public void afterTextChanged( Editable s )
				{
					String strPass1 = p1.getText().toString();
					String strPass2 = p2.getText().toString();
					if ( strPass1.equals( strPass2 ) )
					{
						error.setText( R.string.settings_pwd_match );
					} else
					{
						error.setText( R.string.settings_pwd_not_match );
					}
				}

				// ... other required overrides do nothing
				@Override
				public void beforeTextChanged( CharSequence s, int start,
						int count, int after )
				{
				}

				@Override
				public void onTextChanged( CharSequence s, int start,
						int before, int count )
				{
				}
			} );
			AlertDialog.Builder builder = new AlertDialog.Builder( this );
			builder.setView( layout );
			// Now configure the AlertDialog
			builder.setTitle( R.string.settings_pwd_button );
			builder.setNegativeButton( android.R.string.cancel,
					new DialogInterface.OnClickListener()
					{
						@Override
						public void onClick( DialogInterface dialog,
								int whichButton )
						{
							// We forcefully dismiss and remove the Dialog, so
							// it
							// cannot be used again (no cached info)
							SettingsAct.this.removeDialog( PASSWORD_DIALOG_ID );
						}
					} );
			builder.setPositiveButton( android.R.string.ok,
					new DialogInterface.OnClickListener()
					{
						@Override
						public void onClick( DialogInterface dialog, int which )
						{
							TextView passwordInfo = ( TextView ) findViewById( R.id.textView_pwd_info );
							String strPassword1 = p1.getText().toString();
							String strPassword2 = p2.getText().toString();
							if ( strPassword1.equals( strPassword2 ) )
							{
								Editor editor = mGameSettings.edit();
								editor.putString( GAME_PREFERENCES_PASSWORD,
										strPassword1 );
								editor.commit();
								passwordInfo
										.setText( R.string.settings_pwd_set );
							} else
							{
								Utils.Log(
										"Passwords différents, pas de save, on garde l'ancien (si setté)",
										SettingsAct.this );
							}
							// We forcefully dismiss and remove the Dialog, so
							// it
							// cannot be used again
							SettingsAct.this.removeDialog( PASSWORD_DIALOG_ID );
						}
					} );
			// Create the AlertDialog and return it
			AlertDialog passwordDialog = builder.create();
			return passwordDialog;
		}
		return null;
	}

	@Override
	protected void onPrepareDialog( int id, Dialog dialog )
	{
		Utils.Log( "4", SettingsAct.this );
		super.onPrepareDialog( id, dialog );
		Utils.Log( "5", SettingsAct.this );
		switch ( id )
		{
		/*		case DATE_DIALOG_ID:
					// Handle any DatePickerDialog initialization here
					Utils.Log( "6", SettingsAct.this );
					DatePickerDialog dateDialog = ( DatePickerDialog ) dialog;
					Utils.Log( "7", SettingsAct.this );
					int iDay,
					iMonth,
					iYear;
					// Check for date of birth preference
					if ( mGameSettings.contains( GAME_PREFERENCES_DOB ) )
					{
						// Retrieve Birth date setting from preferences
						long msBirthDate = mGameSettings.getLong( GAME_PREFERENCES_DOB,
								0 );
						Time dateOfBirth = new Time();
						dateOfBirth.set( msBirthDate );
						iDay = dateOfBirth.monthDay;
						iMonth = dateOfBirth.month;
						iYear = dateOfBirth.year;
					} else
					{
						Calendar cal = Calendar.getInstance();
						// Today's date fields
						iDay = cal.get( Calendar.DAY_OF_MONTH );
						iMonth = cal.get( Calendar.MONTH );
						iYear = cal.get( Calendar.YEAR );
					}
					// Set the date in the DatePicker to the date of birth OR to the
					// current date
					dateDialog.updateDate( iYear, iMonth, iDay );
					return;
			*/
		case PASSWORD_DIALOG_ID:
			// Handle any Password Dialog initialization here
			// Since we don't want to show old password dialogs, just set new
			// ones, we need not do anything here
			// Because we are not "reusing" password dialogs once they have
			// finished, but removing them from
			// the Activity Dialog pool explicitly with removeDialog() and
			// recreating them as needed.
			return;
		}
	}

	// /////////////////////////////////////////
	// /////////////////////////////////////////

	@Override
	public void onStart()
	{
		Utils.Log( "Settings onStart", this );
		super.onStart();
	}

	@Override
	public void onResume()
	{
		Utils.Log( "Settings onResume", this );
		super.onResume();
	}

	@Override
	public void onPause()
	{
		Utils.Log( "Settings onPause", this );
		super.onPause();
	}

	@Override
	public void onStop()
	{
		Utils.Log( "Settings onStop", this );
		super.onStop();
	}

	@Override
	public void onDestroy()
	{
		Utils.Log( "Settings onDestroy", this );
		super.onDestroy();

		Log.d( "DEBUG_TAG", "SHARED PREFERENCES" );
		Log.d( "DEBUG_TAG",
				"Nickname is: "
						+ mGameSettings.getString( GAME_PREFERENCES_NICKNAME,
								"Not set" ) );
		Log.d( "DEBUG_TAG",
				"Email is: "
						+ mGameSettings.getString( GAME_PREFERENCES_EMAIL,
								"Not set" ) );
		Log.d( "DEBUG_TAG",
				"Gender (M=1, F=2, U=0) is: "
						+ mGameSettings.getInt( GAME_PREFERENCES_GENDER, 0 ) );
		// We are not saving the password yet
		Log.d( "DEBUG_TAG",
				"Password is: "
						+ mGameSettings.getString( GAME_PREFERENCES_PASSWORD,
								"Not set" ) );
		// We are not saving the date of birth yet
		Log.d( "DEBUG_TAG",
				"DOB is: "
						+ DateFormat.format( "MMMM dd, yyyy",
								mGameSettings.getLong( GAME_PREFERENCES_DOB, 0 ) ) );
		super.onDestroy();
	}
}